<template>
  <div class="import--wrap">
    <div class="table--head">
      <div :style="{ color: '#000', fontSize: '28px', fontWeight: '500' }">
        导出数据
      </div>
      <!-- <div>
        <span :style="{ marginRight: '15px' }">日期选择:</span>
        <a-range-picker v-model:value="dateVal" show-time />
      </div> -->
      <div>
        <a-radio-group v-model:value="type" @change="sexChange">
          <a-radio-button value="ALL">所有</a-radio-button>
          <a-radio-button value="男">男</a-radio-button>
          <a-radio-button value="女">女</a-radio-button>
        </a-radio-group>
      </div>
    </div>
    <div class="table--con">
      <a-table
        :columns="columns"
        :data-source="tableData"
        :row-key="(record) => record.sno"
        :pagination="false"
        :scroll="{ x: 1500, y: 550 }"
      >
        <template #bodyCell="{ column, text }">
          <template v-if="column.dataIndex === 'sex'">
            <a-tag :color="text === '男' ? 'geekblue' : 'volcano'">{{
              text
            }}</a-tag>
          </template>
        </template>
      </a-table>
    </div>
    <div class="pagination--box">
      <a-config-provider>
        <a-pagination
          show-quick-jumper
          v-model="current"
          :page-size-options="pageSizeOptions"
          :total="total"
          show-size-changer
          :page-size="pageSize"
          @showSizeChange="onShowSizeChange"
          @change="handleTableChange"
        >
        </a-pagination>
      </a-config-provider>
    </div>
    <div class="table--upload">
      <div class="upload--filter">
        <a-button type="dashed">导出字段选择</a-button>
        <a-select
          v-model:value="selectVal"
          :options="selectOpt"
          mode="tags"
          placeholder="Please select"
          style="width: 400px"
        ></a-select>
      </div>
      <div class="upload--box">
        <a-button
          type="dashed"
          style="width: 100%; height: 100%"
          @click="exportData"
          >导出数据</a-button
        >
      </div>
    </div>
  </div>
</template>

<script>
import { UploadOutlined } from "@ant-design/icons-vue";
import { exportColumns } from "@/utils";
import { getChineseMedicineByPage } from "@/api";
import * as XLSX from "xlsx";
import moment from "moment";
export default {
  name: "ExportData",
  data() {
    return {
      type: "ALL",
      tableData: [],
      columns: exportColumns,
      dateVal: [],
      total: 0,
      current: 1,
      pageSize: 10,
      pageSizeOptions: ["10", "20", "30"],
      selectedRowKeys: [],
      selectOpt: [
        { name: "name", value: "name" },
        { name: "sex", value: "sex" },
        { name: "pos", value: "pos" },
        { name: "age", value: "age" },
        { name: "department", value: "department" },
        { name: "seen", value: "seen" },
        { name: "tips", value: "tips" },
      ],
      selectVal: ["name", "sex", "tips", "department"],
    };
  },
  computed: {
    rowSelection() {
      return {
        type: "radio",
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange,
      };
    },
  },
  components: {
    UploadOutlined,
  },
  mounted() {
    this.getChineseMedicineByPage();
  },
  methods: {
    async getChineseMedicineByPage() {
      let params = {
        page: this.current,
        limit: this.pageSize,
      };
      if (this.type != "ALL") {
        const where = {
          sex: this.type,
        };
        params.where = where;
      }
      const res = await getChineseMedicineByPage(
        window.CONFIG.server_url,
        params
      );
      if (res.code == 200) {
        this.total = res.data.count;
        this.tableData = res.data.rows;
      }
    },
    onShowSizeChange(current, pageSize) {
      this.pageSize = pageSize;
    },
    handleTableChange(pagination) {
      this.current = pagination;
      this.getChineseMedicineByPage();
      if (this.selectRecord) {
        this.selectedRowKeys = [];
      }
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
    },
    sexChange() {
      this.getChineseMedicineByPage();
    },
    exportData() {
      if (!this.tableData.length) {
        this.$message.error("无数据!");
        return;
      }
      // 默认导出所有字段（如果selectVal为空）
      const fieldsToExport =
        this.selectVal && this.selectVal.length > 0
          ? this.selectVal
          : Object.keys(this.tableData[0]);

      // 中文表头映射（根据你的实际字段调整）
      const chineseHeaders = {
        name: "姓名",
        sex: "性别",
        age: "年龄",
        sn0: "编号",
        department: "科室",
        pos: "部位",
        diagnosis_chinese: "中医诊断",
        diagnosis_western: "西医诊断",
        seen: "症状",
        tips: "医嘱",
      };
      // 1. 准备导出数据（只包含选中的字段）
      const exportData = this.tableData.map((item) => {
        const exportedItem = {};
        fieldsToExport.forEach((field) => {
          exportedItem[chineseHeaders[field] || field] = item[field];
        });
        return exportedItem;
      });
      // 2. 创建工作表
      const ws = XLSX.utils.json_to_sheet(exportData);
      // 3. 创建工作簿
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, "中药数据");
      // 4. 生成Excel文件并下载
      const fileName = `中药数据_${moment().format("YYYY-MM-DD HH:mm:ss")}.xlsx`;
      XLSX.writeFile(wb, fileName);
    },
  },
};
</script>

<style scoped lang="less">
@import "@/assets/import.less";
</style>
